<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-button type="primary" @click="addRoles">添加角色</el-button>
      <!-- 表格 -->
      <el-table stripe border :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['border-bottom', index == 0 ? 'border-top' : '']"
              v-for="(item1, index) of scope.row.children"
              :key="index"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag @close="deleteTag(scope.row, item1.id)" closable>{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row
                  :class="[index1 == 0 ? '' : 'border-top']"
                  v-for="(item2, index1) of item1.children"
                  :key="index1"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      @close="deleteTag(scope.row, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级列表 -->
                    <el-tag
                      @close="deleteTag(scope.row, item3.id)"
                      closable
                      type="warning"
                      v-for="(item3, index2) of item2.children"
                      :key="index2"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              @click="editRoles(scope.row.id)"
              size="mini"
              type="primary"
              icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button
              @click="deleteRoles(scope.row.id)"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              @click="getPower(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialog"
      width="50%"
      @close="addRoleDialogClose"
    >
      <el-form
        :model="addRoleForm"
        :rules="addRoleRules"
        ref="addRoleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoleOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="editRolesDialog"
      width="50%"
      @close="editRoleDialogClose"
    >
      <el-form
        :model="editRoleForm"
        :rules="editRoleRules"
        ref="editRoleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRoleOk(editRoleForm.roleId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog  title="分配权限" :visible.sync="showPowerDialog" width="50%">
      <el-tree
        show-checkbox
        default-expand-all
        :data="allPower"
        :props="defaultProps"
        node-key="id"
        ref="treeRef"
        :default-checked-keys="defaultCheck"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPowerDialog = false">取 消</el-button>
        <el-button type="primary" @click="getPowerOk"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addRolesDialog: false,
      editRolesDialog: false,
      editRoleForm: {
        roleName: "",
        roleDesc: "",
      },
      addRoleForm: {
        roleName: "",
        roleDesc: "",
      },
      addRoleRules: {
        roleName: [
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      editRoleRules: {
        roleName: [
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      showPowerDialog: false,
      // 所有的权限列表
      allPower: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      // 默认选中的
      defaultCheck:[],
      // 要修改的角色权限信息的id
      updataRoleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表信息失败");
      else {
        this.rolesList = res.data;
        // console.log(this.rolesList);
      }
    },
    // 添加角色
    addRoles() {
      this.addRolesDialog = true;
    },
    // 关闭对话框后重置添加角色表单
    addRoleDialogClose() {
      this.$refs.addRoleFormRef.resetFields();
    },
    // 确认添加角色
    async addRoleOk() {
      const { data: res } = await this.$http.post("roles", this.addRoleForm);
      if (res.meta.status !== 201) return this.$message.error("添加角色失败");
      else {
        this.$message.success("添加角色成功");
        this.getRolesList();
        this.addRolesDialog = false;
      }
    },
    // 编辑角色信息
    async editRoles(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取编辑角色信息失败");
      else {
        this.editRoleForm = res.data;
      }
      this.editRolesDialog = true;
    },
    // 关闭对话框后重置编辑角色表单
    editRoleDialogClose() {
      this.$refs.editRoleFormRef.resetFields();
    },
    // 确认修改角色信息
    async editRoleOk(id) {
      const { data: res } = await this.$http.put(
        "roles/" + id,
        this.editRoleForm
      );
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("修改角色信息失败");
      else {
        this.$message.success("修改角色信息成功");
        this.getRolesList();
        this.editRolesDialog = false;
      }
    },
    // 根据id删除角色
    deleteRoles(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("roles/" + id);
          // console.log(res);
          if (res.meta.status !== 200)
            return this.$message.error("删除角色失败");
          else {
            this.$message({
              type: "success",
              message: "删除角色成功!",
            });
            this.getRolesList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async deleteTag(role, rightid) {
      const result = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "删除权限",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(result);
      if (result !== "confirm")
        return this.$message.info("您取消了删除该权限的操作");
      else {
        const { data: res } = await this.$http.delete(
          "roles/" + role.id + "/rights/" + rightid
        );
        if (res.meta.status !== 200)
          return this.$message.error("删除该权限失败");
        else {
          this.$message.success("删除该权限成功");
          role.children = res.data;
        }
      }
    },
    async getPower(checkPower) {
      this.defaultCheck=[]
      this.getCheckId(checkPower,this.defaultCheck)
      // console.log(checkPower);
      // 给当前查看的角色id赋值
      this.updataRoleId=checkPower.id
      const { data: res } = await this.$http.get("rights/tree");
      // console.log(res);
      this.allPower = res.data;
      // console.log(this.allPower);
      // console.log(this.defaultCheck);
      this.showPowerDialog = true;
    },
    getCheckId(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      else{
        node.children.forEach(item=>
        this.getCheckId(item,arr))
      }
    },
    async getPowerOk(){
      const checkAll=this.$refs.treeRef.getCheckedKeys()
      const checkhalf=this.$refs.treeRef.getHalfCheckedKeys()
      // console.log(checkAll);
      // console.log(checkhalf);
      const check2=[]
      const check1=check2.concat(checkAll)
      const check3=check1.concat(checkhalf)
      const check=check3.join(',')
      const {data:res}=await this.$http.post('roles/'+this.updataRoleId+'/rights',{rids:check})
      // console.log(res);
      // console.log(this.updataRoleId);
      if(res.meta.status!==200) return this.$message.error('角色修改权限失败')
      else{
        this.$message.success('角色修改权限成功')
        this.getRolesList()
        this.showPowerDialog=false
      }
    }
  },
};
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.border-top {
  border-top: 1px solid #ccc;
}
.border-bottom {
  border-bottom: 1px solid #ccc;
}
</style>